package cn.edu.zime.tjh.iotapp;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpPost {

    private final OkHttpClient client = new OkHttpClient();


    public void postRequest() {
        // 创建请求体
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        String json = "{\"name\":\"aaa\",\"password\":\"123123\"}";
        RequestBody requestBody = RequestBody.create(json, JSON);

        // 创建请求对象
        Request request = new Request.Builder()
                .url("http://192.168.0.198:8080/user/login")
                .post(requestBody)
                .build();

        // 发起异步请求ixc
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 处理请求失败
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 处理请求成功
                    String responseBody = response.body().string();
                    System.out.println(responseBody);
                } else {
                    // 处理请求失败
                    System.out.println("Request failed: " + response.code());
                }
            }
        });
    }

    public static void main(String[] args) {
        OkHttpPost example = new OkHttpPost();
        example.postRequest();
    }
}
